﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Imaging;
using System.Runtime.InteropServices.WindowsRuntime;

namespace WeixinSB.Tools
{
   public class PicLibrary
    {
       public static async Task Save(UIElement LayoutRoot) 
       {
           // 生成RenderTargetBitmap对象
           RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
           await renderTargetBitmap.RenderAsync(LayoutRoot);
           // 获取图像的二进制数据
           var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();

           //保存相册
           var lib = KnownFolders.PicturesLibrary;
           var saveFile = await lib.CreateFileAsync("weixin_" + DateTime.Now.ToString("yyyy-MM-dd_HHmmss") + ".png", CreationCollisionOption.ReplaceExisting);

           // 把图片的二进制数据写入文件存储
           using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
           {
               var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
               encoder.SetPixelData(
                   BitmapPixelFormat.Bgra8,
                   BitmapAlphaMode.Ignore,
                   (uint)renderTargetBitmap.PixelWidth,
                   (uint)renderTargetBitmap.PixelHeight,
                   DisplayInformation.GetForCurrentView().LogicalDpi,
                   DisplayInformation.GetForCurrentView().LogicalDpi,
                   pixelBuffer.ToArray());

               await encoder.FlushAsync();

               //MessageIn.Begin();
           }
       }
    }
}
